'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 减产士兵
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var buildService = require('../../../../services/buildService');
var taskService = require('../../../../services/taskService');
var roleService = require('../../../../services/roleService');
var soldierConf = require('../../../../config/soldierConf');
var buildType = require('../../../../consts/buildType');
var constantUtil = require('../../../../util/constantUtil');
var PlayerManager = require('../../../../libs/playerManager');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var soldier_type = msg.soldier_type;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['soldier', 'role', 'build', 'accrued'], cb);
            },
            function (cb) {
                var soldier_model = player_manager.soldier;
                var role_model = player_manager.role;

                var soldier_item = soldier_model.getSoldier(soldier_type);
                if (!soldier_item) {
                    return next(null, {
                        code: Code.SOLDIER_NOT_EXIST
                    });
                }

                if (!soldier_model.subProductSoldier(soldier_type, 1)) {
                    return next(null, {
                        code: Code.SOLDIER_NOT_IN_PROTECT
                    });
                }

                if (soldier_model.product_soldier_list.length > 0) {
                    var first_product_soldier_item = soldier_model.product_soldier_list[0];
                    if (first_product_soldier_item.getSoldierType() != soldier_type) {
                        var first_soldier_time_cost = soldierConf.getSoldierProductTime(first_product_soldier_item.getSoldierType());
                        soldier_model.start_product_time = moment();
                        soldier_model.end_product_time = moment(soldier_model.begin_product_time)
                            .add(first_soldier_time_cost, 's');
                    }
                }

                var soldier_type_conf = soldierConf.getSoldierTypeConf(soldier_type);
                roleService.addFoodLimit(player_manager, soldier_type_conf.food_cost);

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
